<template>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <van-icon name="arrow-left" size="30" class="header-left" @click="goBack" />
            订单详情
        </div>
        <!-- 状态栏 -->
        <StatusBar :item="stateMap[detailData.trade_state]" />
        <!-- tip 提示 -->
        <div class="tips">
            <!-- 待支付时显示 -->
            <div class="dzf" v-if="detailData.trade_state == '待支付'">
                <div class="text1">订单待支付</div>
                <div class="text2">请在
                    <Counter :second="timer" />内完成支付，超时订单自动取消
                </div>
                <div class="text3">
                    <van-button type="success" @click="openCode">立即支付(0.5元)</van-button>
                </div>
            </div>
            <!-- 待服务时显示 -->
            <div class="dzf" v-if="detailData.trade_state == '待服务'">
                <div class="text1">正在为您安排服务专员...</div>
                <div class="text2">请保持手机畅通，稍后将有服务专员与你联系</div>
            </div>
            <!-- 已完成时显示 -->
            <div class="dzf" v-if="detailData.trade_state == '已完成'">
                <div class="text1">服务已完成</div>
                <div class="text2">感谢您的使用，如有售后问题请联系客服</div>
            </div>
            <!-- 已取消时显示 -->
            <div class="dzf" v-if="detailData.trade_state == '已取消'">
                <div class="text1">订单已取消</div>
                <div class="text2">期待下次为你服务，如需帮助可咨询客服</div>
            </div>
        </div>

        <!-- 预约信息 -->
        <van-cell-group class="card">
            <div class="header-text">预约信息</div>
            <van-cell v-for="(item, key) in makeInfo" :key="key" :title="item" :value="formatData(key)" />
        </van-cell-group>

        <!-- 订单信息 -->
        <van-cell-group class="card">
            <div class="header-text">订单信息</div>
            <van-cell v-for="(item, key) in orderInfo" :key="key" :title="item" :value="formatData(key)" />
            <van-cell title="联系客服" value="疑问或投诉" is-link />
        </van-cell-group>

        <!-- 微信支付二维码弹窗 -->
        <van-dialog v-model:show="showCode" :show-confirm-button="false">
            <van-icon name="cross" class="close" @click="showCode = false" />
            <div>微信支付</div>
            <van-image :src="codeImg" width="150" height="150" />
            <div>请使用微信扫一扫</div>
        </van-dialog>
    </div>
</template>

<script setup name="detail">
import StatusBar from '../../components/statusBar.vue' // 状态栏组件
import { ref, reactive, getCurrentInstance, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Counter from '../../components/counter.vue' // 倒计时组件
import QRCode from 'qrcode' // 引入微信支付插件
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

// 订单详情
const detailData = reactive({})
// 微信支付二维码
const showCode = ref(false)
const codeImg = ref('')

// 打开二维码弹窗
const openCode = () => {
    showCode.value = true
    checkPaymentStatus(detailData.out_trade_no)
}

// 订单状态
const stateMap = {
    '待支付': 10,
    '待服务': 20,
    '已完成': 30,
    '已取消': 40,
}

// 点击返回上一页
const goBack = () => {
    router.go(-1)
}
// 倒计时
const timer = computed(() => {
    return detailData.order_start_time ? detailData.order_start_time + 7200000 - Date.now() : 0
})

// 预约信息
const makeInfo = {
    service_name: '预约服务',
    hospital_name: '就诊医院',
    starttime: '期望就诊时间',
    'client.name': '就诊人',
    'client.mobile': '就诊人电话',
    receiveAddress: '接送地址',
    demand: '其他需求',
}

// 订单信息
const orderInfo = {
    tel: '联系电话',
    order_start_time: '下单时间',
    price: '应付金额',
    out_trade_no: '订单编号',
}

// 格式化信息数据输出
const formatData = (key) => {
    if (key.indexOf(".") === -1) {
        if (key === "order_start_time") {
            return formatTimestamp(detailData[key]);
        }
        return detailData[key];
    }
    // ['client','mobile']
    // 有起始值时 累计值初始值为起始值
    // 无起始值时 累计值初始值为数组的第一个元素
    // prev迭代累计值 item 当前数组元素 detailData初始值
    // 第一轮 prev = detailData[client]
    // 第二轮 prev = detailData[client][mobile]
    let arr = key.split(".").reduce((prev, item) => {
        return (prev || {})[item];
    }, detailData);
    return arr;
}
// 格式化时间
function formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以需要+1
    const day = String(date.getDate()).padStart(2, "0"); // padStart 用0进行头部补全

    return `${year}-${month}-${day}`;
}

onMounted(async () => {
    const { data } = await proxy.$api.orderDetail({ oid: route.query.oid })
    console.log(data)
    Object.assign(detailData, data.data)
    // 生成二维码
    QRCode.toDataURL(detailData.code_url).then((qrcoderUrl) => {
        codeImg.value = qrcoderUrl // 设置二维码图片
    })
})
//  检查支付状态
const checkPaymentStatus = async (orderId) => {
    let timeout = 60 // 设置最大等待时间（秒）
    let elapsed = 0

    const interval = setInterval(async () => {
        try {
            // 获取当前订单详情
            const res = await proxy.$api.orderDetail({ oid: orderId })
            // 如果订单已支付
            if (res.data.trade_state === '已完成') {
                clearInterval(interval)
                showCode.value = false
                router.push('/order')
            }
            elapsed += 3
            // 超时
            if (elapsed >= timeout) {
                clearInterval(interval)
                showCode.value = false
                alert('支付超时，请重新支付')
            }
        } catch (err) {
            console.error('查询失败:', err)
        }
    }, 3000)
}
</script>

<style lang="less" scoped>
.container {
    background-color: #f0f0f0;
    height: 100vh;
}

.header {
    background-color: #fff;
    line-height: 40px;
    text-align: center;

    .header-left {
        float: left;
    }
}

.card {
    margin: 15px 0;
    padding: 10px;

    .header-text {
        padding-left: 5px;
        line-height: 30px;
        font-size: 16px;
        font-weight: bold;
        border-left: 4px solid red;
    }
}

.dzf {
    padding: 20px;

    .text1 {
        font-size: 20px;
        font-weight: bold;
        line-height: 30px;
        color: #666;
    }

    .text2 {
        font-size: 14px;
        color: #666;
    }

    .text3 {
        text-align: center;

        .van-button {
            margin-top: 10px;
            margin-left: 10px;
            width: 80%;
            font-weight: bold;
        }
    }
}

::v-deep(.van-dialog__content) {
    text-align: center;
    padding: 20px;

    .close {
        position: absolute;
        left: 20px;
    }
}
</style>